package com.caigp.cookbook2.base;

import androidx.annotation.NonNull;
import androidx.appcompat.app.ActionBar;
import androidx.appcompat.app.AppCompatActivity;
import android.os.Bundle;
import android.view.MenuItem;
import com.caigp.cookbook2.bean.Favorite;
import com.caigp.cookbook2.util.AssetsUtil;
import org.litepal.LitePal;
import java.util.ArrayList;
import java.util.Collections;
import java.util.List;

public abstract class BaseActivity extends AppCompatActivity {

    public List<String> cookNameList;

    public ActionBar actionBar;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setMyActionBar();
        findFavorite();
        initCookName();
    }

    private void setMyActionBar() {
        actionBar = getSupportActionBar();
        actionBar.setDisplayHomeAsUpEnabled(showHomeAsUp());
    }

    public void setActionBarTitle(CharSequence title) {
        actionBar.setTitle(title);
    }

    protected abstract boolean showHomeAsUp();

    public List<Favorite> findFavorite() {
        return LitePal.findAll(Favorite.class);
    }

    @Override
    public boolean onOptionsItemSelected(@NonNull MenuItem item) {
        switch (item.getItemId()) {
            case android.R.id.home:
                onBackPressed();
                break;
        }
        return super.onOptionsItemSelected(item);
    }

    /**
     * 删除指定iid的收藏
     * @param iid
     */
    public boolean deleteFavorite(String iid) {
        int row = LitePal.deleteAll(Favorite.class, "iid = ?", iid);
        if (row > 0) {
            return true;
        }
        return false;
    }

    private void initCookName() {
        cookNameList = AssetsUtil.getList(this, "cook_name.txt");
    }

    /**
     * 获取首页的热搜词
     * @return
     */
    public List<String> hotList() {
        List<String> list = new ArrayList<>();
        Collections.shuffle(cookNameList);
        for (int i = 0; i < 12; i++) {
            list.add(cookNameList.get(i));
        }
        return list;
    }
}
